package com.hh.controller;

import com.hh.common.BaseResponse;
import com.hh.common.ResultUtils;
import com.hh.entity.domain.Message;
import com.hh.entity.domain.User;
import com.hh.service.MessageService;
import com.hh.service.UserService;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author hanhui
 * @version 1.0
 * @description: TODO
 * @date 2025/9/24 21:35
 **/

@RestController
@RequestMapping("/messages")
public class MessageController {

    @Resource
    private MessageService messageService;
    @Resource
    private UserService userService;
    @Resource
    private SimpMessagingTemplate messagingTemplate;

    @PostMapping("/send")
    public void sendNotificationToUser(@RequestBody Message message) {
        // 发送消息到指定用户的队列
        // 对应前端订阅的 /user/${userId}/queue/notifications
        messagingTemplate.convertAndSendToUser(
                message.getUserId().toString(),
                "/queue/notifications",
                message.getContent()
        );
    }

    /**
     * 获取当前用户的消息列表
     */
    @GetMapping
    public BaseResponse<List<Message>> getMyMessages(HttpServletRequest request) {
        String userId = getCurrentUserId(request);
        List<Message> userMessages = messageService.getUserMessages(userId);
        return ResultUtils.success(userMessages);
    }

    /**
     * 将消息标记为已读
     */
    @PutMapping("/{id}/read")
    public BaseResponse<Boolean> markAsRead(@PathVariable Long id) {
        int isRead = messageService.markAsRead(id);
        return ResultUtils.success(isRead > 0);
    }

    /**
     * 将消息标记为已读
     */
    @PutMapping("/readAll")
    public BaseResponse<Boolean> ReadAll(HttpServletRequest request) {
        int isRead = messageService.readAll(request);
        return ResultUtils.success(isRead > 0);
    }
    /**
     * 获取未读消息数量
     */
    @GetMapping("/unread/count")
    public BaseResponse<Long> getUnreadCount(HttpServletRequest request) {
        String userId = getCurrentUserId(request);
        long unreadCount = messageService.getUnreadCount(userId);
        return ResultUtils.success(unreadCount);
    }

    // 获取当前登录用户ID（实际项目中应根据认证方式实现）
    private String getCurrentUserId(HttpServletRequest request) {
        // 这里简化处理，实际项目中应从SecurityContext或Token中获取
        User loginUser = userService.getLoginUser(request);
        return loginUser.getId().toString();
    }
}
